package main

import (
	"fmt"
	"sync"
	"time"
)

//type atomicInt int
//
//func (a *atomicInt) increment() {
//	*a++
//}
//
//func (a *atomicInt) get() int {
//	return int(*a)
//}
//
//// go run -race atomic.go
//func main() {
//	var a atomicInt
//	a.increment()
//	go func() {
//		a.increment()
//	}()
//	time.Sleep(time.Millisecond)
//	fmt.Println(a)
//}

// #2
type atomicInt struct {
	value int
	lock  sync.Mutex
}

func (a *atomicInt) increment() {
	//a.lock.Lock()
	//defer a.lock.Unlock() // defer保证在整个函数范围
	//a.value++

	// 如果要在代码块加锁，可以使用匿名函数
	fmt.Println("safe increment")
	func() {
		a.lock.Lock()
		defer a.lock.Unlock()

		a.value++
	}()
}

func (a *atomicInt) get() int {
	a.lock.Lock()
	defer a.lock.Unlock()
	return a.value
}

// go run -race atomic.go
func main() {
	var a atomicInt
	a.increment()
	go func() {
		a.increment()
	}()
	time.Sleep(time.Millisecond)
	fmt.Println(a.get())
}
